package cn.kent.base.wait;


/**
 * 当线程调用共享对象的wait（）方法时，当前线程只会释放当前共享对象的锁，当前线程持有的其他共享对象的监视器锁并不会被释放。
 *
 * 以下代码验证了上述
 */
public class Weakup {
    private static volatile Object resoureA = new Object();
    private static volatile Object resoureB = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 获取A的监视器锁
                    synchronized (resoureA) {
                        System.out.println("threadA get resource A lock");
                        // 获取B的监视器锁
                        synchronized (resoureB) {
                            System.out.println("threadA get resource B lock");
                            // 线程A 阻塞，并释放获取到的A的锁
                            System.out.println("threadA release resource A lock");
                            resoureA.wait();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);// 休息一秒
                    // 获取A的监视器锁
                    synchronized (resoureA) {
                        System.out.println("threadB get resource A lock");
                        System.out.println("threadB try get resource B lock");
                        // 获取B的锁
                        synchronized (resoureB) {
                            System.out.println("threadB get resource B lock");
                            // 线程B阻塞并释放A的锁
                            System.out.println("threadB release resource A lock");
                            resoureA.wait();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        // 启动线程
        threadA.start();
        threadB.start();
        // 等待两个线程结束
        threadA.join();
        threadB.join();
        System.out.println("main over");
    }
}
